package nkr1pt.popkorn.download;

import java.io.File;
import nkr1pt.popkorn.helper.FileUtils;
import nkr1pt.popkorn.helper.URLWrapper;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Kristof Vanhaeren
 */
public class DownloadCandidateItem {

    private DownloadCandidate downloadCandidate;
    private URLWrapper url;
    private String name;
    private Long size = 0L;
    private long downloaded = 0L;
    private DownloadCandidateState state;
    private String cookie;

    public DownloadCandidateItem(DownloadCandidate downloadCandidate, URLWrapper url) {
        this.downloadCandidate = downloadCandidate;
        this.url = url;
        this.name = FilenameUtils.getName(url.getFile());
        this.downloaded = new File(getAbsolutePath()).length();
        setInitialState();
    }

    public URLWrapper getUrl() {
        return url;
    }

    public DownloadCandidateState getState() {
        return state;
    }

    public void setState(DownloadCandidateState state) {
        this.state = state;
    }

    public DownloadCandidate getDownloadCandidate() {
        return downloadCandidate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAbsolutePath() {
        return downloadCandidate.getCurrentLocation() + File.separator + downloadCandidate.getName() + File.separator + name;
    }

    public String getSimpleName() {
        return FilenameUtils.getName(getName());
    }

    /** the size in bytes */
    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public long getDownloaded() {
        return downloaded;
    }

    public void setDownloaded(long downloaded) {
        this.downloaded = downloaded;
    }

    public String getCookie() {
        return cookie;
    }

    public void setCookie(String cookie) {
        this.cookie = cookie;
    }

    private void setInitialState() {
        state = DownloadCandidateState.WAITING;

        if (FileUtils.isAccessable(new File(name)) &&
                size == downloaded &&
                size != 0L) {
            state = DownloadCandidateState.COMPLETE;
        }
    }

}